<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深拷贝</title>
</head>
<body>
    <script>
        //1.深拷贝传统方法, new Map() 方法遍历每个属性
        function deepClone(obj){
            const objectMap = new Map()
            const _deepClone = (value) => {
                const type = typeof value
                if( type !== 'object' || type === null) {
                    return value
                }
                if (objectMap.has(value)) {
                    return objectMap.get(value)   //如果是循环引用, 就返回对象本身
                }
                const result = Array.isArray(value) ? [] : {}
                objectMap.set(value, result)
                for(const key in value){
                    result[key] = _deepClone(value[key])
                }
                return result
            }
            return _deepClone(obj)
        }
        let obj 
        obj = {
            a:1,b:2,c: obj
        } 
        obj.c = obj //循环引用

        //验证1
        let obj2 = deepClone(obj)
        obj.a=333
        console.log(obj2);

        //2.深拷贝 new MessageChannel()方法 , MessageChannel定义两个端口,可以互相传递数据, 接收到的数据是一个深拷贝后的数据
        function deepClone2(obj){
            return new Promise((resolve, reject) => {
                const {port1, port2} = new MessageChannel()
                port1.postMessage(obj)
                port2.onmessage = (msg) => {
                    resolve(msg.data)
                }
            })
        }
        //验证2
        deepClone2(obj).then(res => {
            obj.a=44444
            console.log(res);
        })
    </script>
</body>
</html>